home *** CD-ROM | disk | FTP | other *** search
/ Visual Cafe 3 / Visual Cafe 3.ISO / Vcafe / Sample.bin / XYZApp.java < prev    next >
Text File  |  1998-09-15  |  14KB  |  521 lines

  1. /*
  2.  * @(#)XYZApp.java    1.4 97/07/28
  3.  *
  4.  * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
  5.  *
  6.  * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
  7.  * modify and redistribute this software in source and binary code form,
  8.  * provided that i) this copyright notice and license appear on all copies of
  9.  * the software; and ii) Licensee does not utilize the software in a manner
  10.  * which is disparaging to Sun.
  11.  *
  12.  * This software is provided "AS IS," without a warranty of any kind. ALL
  13.  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
  14.  * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
  15.  * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
  16.  * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
  17.  * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
  18.  * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
  19.  * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
  20.  * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
  21.  * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
  22.  * POSSIBILITY OF SUCH DAMAGES.
  23.  *
  24.  * This software is not designed or intended for use in on-line control of
  25.  * aircraft, air traffic, aircraft navigation or aircraft communications; or in
  26.  * the design, construction, operation or maintenance of any nuclear
  27.  * facility. Licensee represents and warrants that it will not use or
  28.  * redistribute the Software for such purposes.
  29.  */
  30.  
  31. /*
  32.  * A set of classes to parse, represent and display Chemical compounds in
  33.  * .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html)
  34.  */
  35.  
  36. import java.applet.Applet;
  37. import java.awt.Image;
  38. import java.awt.Event;
  39. import java.awt.Graphics;
  40. import java.awt.Dimension;
  41. import java.io.*;
  42. import java.net.URL;
  43. import java.util.Hashtable;
  44. import java.awt.image.IndexColorModel;
  45. import java.awt.image.ColorModel;
  46. import java.awt.image.MemoryImageSource;
  47. import java.awt.event.*;
  48.  
  49. /** The representation of a Chemical .xyz model */
  50. class XYZChemModel {
  51.     float vert[];
  52.     Atom atoms[];
  53.     int tvert[];
  54.     int ZsortMap[];
  55.     int nvert, maxvert;
  56.  
  57.     static Hashtable atomTable = new Hashtable();
  58.     static Atom defaultAtom;
  59.     static {
  60.     atomTable.put("c", new Atom(0, 0, 0));
  61.     atomTable.put("h", new Atom(210, 210, 210));
  62.     atomTable.put("n", new Atom(0, 0, 255));
  63.     atomTable.put("o", new Atom(255, 0, 0));
  64.     atomTable.put("p", new Atom(255, 0, 255));
  65.     atomTable.put("s", new Atom(255, 255, 0));
  66.     atomTable.put("hn", new Atom(150, 255, 150)); /* !!*/
  67.     defaultAtom = new Atom(255, 100, 200);
  68.     }
  69.  
  70.     boolean transformed;
  71.     Matrix3D mat;
  72.  
  73.     float xmin, xmax, ymin, ymax, zmin, zmax;
  74.  
  75.  
  76.     XYZChemModel () {
  77.     mat = new Matrix3D();
  78.     mat.xrot(20);
  79.     mat.yrot(30);
  80.     }
  81.  
  82.  
  83.     /** Create a Cehmical model by parsing an input stream */
  84.     XYZChemModel (InputStream is) throws Exception
  85.     {
  86.        this();
  87.        StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(is)));
  88.        st.eolIsSignificant(true);
  89.        st.commentChar('#');
  90.        int slot = 0;
  91.       
  92.        try
  93.        {
  94. scan:
  95.           while (true)
  96.           {
  97.              switch ( st.nextToken() ) 
  98.              {
  99.                 case StreamTokenizer.TT_EOF:
  100.                    break scan;
  101.                 default:
  102.                    break;
  103.                 case StreamTokenizer.TT_WORD:
  104.                    String name = st.sval;
  105.                    double x = 0, y = 0, z = 0;
  106.                    if (st.nextToken() == StreamTokenizer.TT_NUMBER) 
  107.                    {
  108.                       x = st.nval;
  109.                       if (st.nextToken() == StreamTokenizer.TT_NUMBER) 
  110.                       {
  111.                          y = st.nval;
  112.                          if (st.nextToken() == StreamTokenizer.TT_NUMBER)
  113.                             z = st.nval;
  114.                       }
  115.                    }
  116.                    addVert(name, (float) x, (float) y, (float) z);
  117.                    while( st.ttype != StreamTokenizer.TT_EOL &&
  118.                           st.ttype != StreamTokenizer.TT_EOF )
  119.                       st.nextToken();
  120.  
  121.              }   // end Switch
  122.  
  123.           }  // end while
  124.  
  125.           is.close();
  126.  
  127.        }  // end Try
  128.        catch( IOException e) {}
  129.  
  130.        if (st.ttype != StreamTokenizer.TT_EOF)
  131.           throw new Exception(st.toString());
  132.  
  133.     }  // end XYZChemModel()
  134.  
  135.     /** Add a vertex to this model */
  136.     int addVert(String name, float x, float y, float z) {
  137.     int i = nvert;
  138.     if (i >= maxvert)
  139.         if (vert == null) {
  140.         maxvert = 100;
  141.         vert = new float[maxvert * 3];
  142.         atoms = new Atom[maxvert];
  143.         } else {
  144.         maxvert *= 2;
  145.         float nv[] = new float[maxvert * 3];
  146.         System.arraycopy(vert, 0, nv, 0, vert.length);
  147.         vert = nv;
  148.         Atom na[] = new Atom[maxvert];
  149.         System.arraycopy(atoms, 0, na, 0, atoms.length);
  150.         atoms = na;
  151.         }
  152.     Atom a = (Atom) atomTable.get(name.toLowerCase());
  153.     if (a == null) a = defaultAtom;
  154.     atoms[i] = a;
  155.     i *= 3;
  156.     vert[i] = x;
  157.     vert[i + 1] = y;
  158.     vert[i + 2] = z;
  159.     return nvert++;
  160.     }
  161.  
  162.     /** Transform all the points in this model */
  163.     void transform() {
  164.     if (transformed || nvert <= 0)
  165.         return;
  166.     if (tvert == null || tvert.length < nvert * 3)
  167.         tvert = new int[nvert * 3];
  168.     mat.transform(vert, tvert, nvert);
  169.     transformed = true;
  170.     }
  171.  
  172.  
  173.     /** Paint this model to a graphics context.  It uses the matrix associated
  174.     with this model to map from model space to screen space.
  175.     The next version of the browser should have double buffering,
  176.     which will make this *much* nicer */
  177.     void paint(Graphics g) {
  178.     if (vert == null || nvert <= 0)
  179.         return;
  180.     transform();
  181.     int v[] = tvert;
  182.     int zs[] = ZsortMap;
  183.     if (zs == null) {
  184.         ZsortMap = zs = new int[nvert];
  185.         for (int i = nvert; --i >= 0;)
  186.         zs[i] = i * 3;
  187.     }
  188.  
  189.     /*
  190.      * I use a bubble sort since from one iteration to the next, the sort
  191.      * order is pretty stable, so I just use what I had last time as a
  192.      * "guess" of the sorted order.  With luck, this reduces O(N log N)
  193.      * to O(N)
  194.      */
  195.  
  196.     for (int i = nvert - 1; --i >= 0;) {
  197.         boolean flipped = false;
  198.         for (int j = 0; j <= i; j++) {
  199.         int a = zs[j];
  200.         int b = zs[j + 1];
  201.         if (v[a + 2] > v[b + 2]) {
  202.             zs[j + 1] = a;
  203.             zs[j] = b;
  204.             flipped = true;
  205.         }
  206.         }
  207.         if (!flipped)
  208.         break;
  209.     }
  210.  
  211.     int lg = 0;
  212.     int lim = nvert;
  213.     Atom ls[] = atoms;
  214.     if (lim <= 0 || nvert <= 0)
  215.         return;
  216.     for (int i = 0; i < lim; i++) {
  217.         int j = zs[i];
  218.         int grey = v[j + 2];
  219.         if (grey < 0)
  220.         grey = 0;
  221.         if (grey > 15)
  222.         grey = 15;
  223.         // g.drawString(names[i], v[j], v[j+1]);
  224.         atoms[j/3].paint(g, v[j], v[j + 1], grey);
  225.         // g.drawImage(iBall, v[j] - (iBall.width >> 1), v[j + 1] -
  226.         // (iBall.height >> 1));
  227.     }
  228.     }
  229.  
  230.     /** Find the bounding box of this model */
  231.     void findBB() {
  232.     if (nvert <= 0)
  233.         return;
  234.     float v[] = vert;
  235.     float xmin = v[0], xmax = xmin;
  236.     float ymin = v[1], ymax = ymin;
  237.     float zmin = v[2], zmax = zmin;
  238.     for (int i = nvert * 3; (i -= 3) > 0;) {
  239.         float x = v[i];
  240.         if (x < xmin)
  241.         xmin = x;
  242.         if (x > xmax)
  243.         xmax = x;
  244.         float y = v[i + 1];
  245.         if (y < ymin)
  246.         ymin = y;
  247.         if (y > ymax)
  248.         ymax = y;
  249.         float z = v[i + 2];
  250.         if (z < zmin)
  251.         zmin = z;
  252.         if (z > zmax)
  253.         zmax = z;
  254.     }
  255.     this.xmax = xmax;
  256.     this.xmin = xmin;
  257.     this.ymax = ymax;
  258.     this.ymin = ymin;
  259.     this.zmax = zmax;
  260.     this.zmin = zmin;
  261.     }
  262. }
  263.  
  264. /** An applet to put a Chemical model into a page */
  265. public class XYZApp
  266.     extends Applet 
  267.     implements Runnable, MouseListener, MouseMotionListener {
  268.     XYZChemModel md;
  269.     boolean painted = true;
  270.     float xfac;
  271.     int prevx, prevy;
  272.     float xtheta, ytheta;
  273.     float scalefudge = 1;
  274.     Matrix3D amat = new Matrix3D(), tmat = new Matrix3D();
  275.     String mdname = null;
  276.     String message = null;
  277.     Image backBuffer;
  278.     Graphics backGC;
  279.     Dimension backSize;
  280.  
  281.  
  282.     private synchronized void newBackBuffer() {
  283.     backBuffer = createImage(getSize().width, getSize().height);
  284.     backGC = backBuffer.getGraphics();
  285.     backSize = getSize();
  286.     }
  287.  
  288.     public void init() {
  289.     mdname = getParameter("model");
  290.     try {
  291.         scalefudge = Float.valueOf(getParameter("scale")).floatValue();
  292.     } catch(Exception e) {
  293.     };
  294.     amat.yrot(20);
  295.     amat.xrot(20);
  296.     if (mdname == null)
  297.         mdname = "model.obj";
  298.     resize(getSize().width <= 20 ? 400 : getSize().width,
  299.            getSize().height <= 20 ? 400 : getSize().height);
  300.     newBackBuffer();
  301.     addMouseListener(this);
  302.     addMouseMotionListener(this);
  303.     }
  304.  
  305.     public void destroy() {
  306.         removeMouseListener(this);
  307.         removeMouseMotionListener(this);
  308.     }
  309.  
  310.     public void run() {
  311.     InputStream is = null;
  312.     try {
  313.         Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
  314.         is = new URL(getDocumentBase(), mdname).openStream();
  315.         XYZChemModel m = new XYZChemModel (is);
  316.         Atom.setApplet(this);
  317.         md = m;
  318.         m.findBB();
  319.         float xw = m.xmax - m.xmin;
  320.         float yw = m.ymax - m.ymin;
  321.         float zw = m.zmax - m.zmin;
  322.         if (yw > xw)
  323.         xw = yw;
  324.         if (zw > xw)
  325.         xw = zw;
  326.         float f1 = getSize().width / xw;
  327.         float f2 = getSize().height / xw;
  328.         xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge;
  329.     } catch(Exception e) {
  330.         e.printStackTrace();
  331.         md = null;
  332.         message = e.toString();
  333.     }
  334.     try {
  335.         if (is != null)
  336.         is.close();
  337.     } catch(Exception e) {
  338.     }
  339.     repaint();
  340.     }
  341.     public void start() {
  342.     if (md == null && message == null)
  343.         new Thread(this).start();
  344.     }
  345.     public void stop() {
  346.     }
  347.       /* event handling */
  348.   public void mouseClicked(MouseEvent e) {
  349.   }   
  350.   public void mousePressed(MouseEvent e) {
  351.     prevx = e.getX();
  352.     prevy = e.getY();
  353.     e.consume();  
  354.   } 
  355.   public void mouseReleased(MouseEvent e) {
  356.   }
  357.   public void mouseEntered(MouseEvent e) {
  358.   }
  359.   public void mouseExited(MouseEvent e) {
  360.   }   
  361.   public void mouseDragged(MouseEvent e) {
  362.     int x = e.getX();
  363.     int y = e.getY();
  364.     tmat.unit();
  365.     float xtheta = (prevy - y) * (360.0f / getSize().width);
  366.     float ytheta = (x - prevx) * (360.0f / getSize().height);
  367.     tmat.xrot(xtheta);
  368.     tmat.yrot(ytheta);
  369.     amat.mult(tmat);
  370.     if (painted) {
  371.       painted = false;
  372.       repaint();
  373.     }
  374.     prevx = x;
  375.     prevy = y;
  376.     e.consume();
  377.   }
  378.   public void mouseMoved(MouseEvent e) { 
  379.   }
  380.      
  381.     public void update(Graphics g) {
  382.     if (backBuffer == null)
  383.         g.clearRect(0, 0, getSize().width, getSize().height);
  384.     paint(g);
  385.     }
  386.  
  387.     public void paint(Graphics g) {
  388.     if (md != null) {
  389.         md.mat.unit();
  390.         md.mat.translate(-(md.xmin + md.xmax) / 2,
  391.                  -(md.ymin + md.ymax) / 2,
  392.                  -(md.zmin + md.zmax) / 2);
  393.         md.mat.mult(amat);
  394.         // md.mat.scale(xfac, -xfac, 8 * xfac / getSize().width);
  395.         md.mat.scale(xfac, -xfac, 16 * xfac / getSize().width);
  396.         md.mat.translate(getSize().width / 2, getSize().height / 2, 8);
  397.         md.transformed = false;
  398.         if (backBuffer != null) {
  399.         if (!backSize.equals(getSize()))
  400.             newBackBuffer();
  401.         backGC.setColor(getBackground());
  402.         backGC.fillRect(0,0,getSize().width,getSize().height);
  403.         md.paint(backGC);
  404.         g.drawImage(backBuffer, 0, 0, this);
  405.         }
  406.         else
  407.         md.paint(g);
  408.         setPainted();
  409.     } else if (message != null) {
  410.         g.drawString("Error in model:", 3, 20);
  411.         g.drawString(message, 10, 40);
  412.     }
  413.     }
  414.     private synchronized void setPainted() {
  415.     painted = true;
  416.     notifyAll();
  417.     }
  418.  
  419.     private synchronized void waitPainted() 
  420.     {
  421.        while (!painted)
  422.        {
  423.           try
  424.           {
  425.              wait();
  426.           }
  427.           catch (InterruptedException e) {}
  428.        }
  429.        painted = false;
  430.     }
  431.  
  432.   public String getAppletInfo() {
  433.     return "Title: XYZApp \nAuthor: James Gosling \nAn applet to put a Chemical model into a page.";
  434.   }
  435.   
  436.   public String[][] getParameterInfo() {
  437.     String[][] info = {
  438.       {"model", "path string", "The path to the model to be displayed in .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html).  Default is model.obj."},
  439.       {"scale", "float", "Scale factor.  Default is 1 (i.e. no scale)."}
  440.     };
  441.     return info;
  442.   }
  443. }   // end class XYZApp
  444.  
  445. class Atom {
  446.     private static Applet applet;
  447.     private static byte[] data;
  448.     private final static int R = 40;
  449.     private final static int hx = 15;
  450.     private final static int hy = 15;
  451.     private final static int bgGrey = 192;
  452.     private final static int nBalls = 16;
  453.     private static int maxr;
  454.  
  455.     private int Rl;
  456.     private int Gl;
  457.     private int Bl;
  458.     private Image balls[];
  459.  
  460.     static {
  461.     data = new byte[R * 2 * R * 2];
  462.     int mr = 0;
  463.     for (int Y = 2 * R; --Y >= 0;) {
  464.         int x0 = (int) (Math.sqrt(R * R - (Y - R) * (Y - R)) + 0.5);
  465.         int p = Y * (R * 2) + R - x0;
  466.         for (int X = -x0; X < x0; X++) {
  467.         int x = X + hx;
  468.         int y = Y - R + hy;
  469.         int r = (int) (Math.sqrt(x * x + y * y) + 0.5);
  470.         if (r > mr)
  471.             mr = r;
  472.         data[p++] = r <= 0 ? 1 : (byte) r;
  473.         }
  474.     }
  475.     maxr = mr;
  476.     }
  477.     static void setApplet(Applet app) {
  478.     applet = app;
  479.     }
  480.     Atom(int Rl, int Gl, int Bl) {
  481.     this.Rl = Rl;
  482.     this.Gl = Gl;
  483.     this.Bl = Bl;
  484.     }
  485.     private final int blend(int fg, int bg, float fgfactor) {
  486.     return (int) (bg + (fg - bg) * fgfactor);
  487.     }
  488.     private void Setup() {
  489.     balls = new Image[nBalls];
  490.     byte red[] = new byte[256];
  491.     red[0] = (byte) bgGrey;
  492.     byte green[] = new byte[256];
  493.     green[0] = (byte) bgGrey;
  494.     byte blue[] = new byte[256];
  495.     blue[0] = (byte) bgGrey;
  496.     for (int r = 0; r < nBalls; r++) {
  497.         float b = (float) (r+1) / nBalls;
  498.         for (int i = maxr; i >= 1; --i) {
  499.         float d = (float) i / maxr;
  500.         red[i] = (byte) blend(blend(Rl, 255, d), bgGrey, b);
  501.         green[i] = (byte) blend(blend(Gl, 255, d), bgGrey, b);
  502.         blue[i] = (byte) blend(blend(Bl, 255, d), bgGrey, b);
  503.         }
  504.         IndexColorModel model = new IndexColorModel(8, maxr + 1,
  505.                             red, green, blue, 0);
  506.         balls[r] = applet.createImage(
  507.         new MemoryImageSource(R*2, R*2, model, data, 0, R*2));
  508.     }
  509.     }
  510.     void paint(Graphics gc, int x, int y, int r) {
  511.     Image ba[] = balls;
  512.     if (ba == null) {
  513.         Setup();
  514.         ba = balls;
  515.     }
  516.     Image i = ba[r];
  517.     int size = 10 + r;
  518.     gc.drawImage(i, x - (size >> 1), y - (size >> 1), size, size, applet);
  519.     }
  520. }
  521.